import { ref } from 'vue'

import { catchFn } from '@/libs/common'
import { getConsumeList } from './api'

let page = 0
const list = ref<
  {
    name: string
    balanceDesc: string
    changeAmountDesc: string
    createdTime: string
  }[]
>([])
const isBottom = ref(false)
const isUpdating = ref(false)

export { list, isBottom, isUpdating }

/**
 * 更新消费记录
 */
const update = async () => {
  if (isUpdating.value || isBottom.value) return
  else isUpdating.value = true

  await catchFn(async () => {
    const { data } = await getConsumeList(++page)

    list.value.push(
      ...data.list.map(item => ({
        name: item.remark,
        balanceDesc: item.balanceDesc,
        changeAmountDesc: item.changeAmountDesc,
        createdTime: item.createdTime,
      })),
    )
    isBottom.value = !data.hasNext
  })

  isUpdating.value = false
}

/**
 * 还原状态
 */
const clear = () => {
  page = 0
  isUpdating.value = false
  isBottom.value = false
  list.value = []
}

export { update, clear }
